package com.sc.site.spring;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.sc.dal.dto.member.AgentDto;
import com.sc.util.data.CookieUtils;
import com.sc.util.data.SessionContainer;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	/**
	 * 
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//获取sessionId
		String SID = request.getSession().getId();
		AgentDto memberFromCookies=(AgentDto) CookieUtils.getCookieEntity(request, SessionContainer.MEMBER_INFO, AgentDto.class);
		AgentDto memberFromSession=(AgentDto) request.getSession().getAttribute(SessionContainer.sessionID + SID);
		if(memberFromCookies==null&&memberFromSession==null){
		//	System.out.println(request.getContextPath());
			response.sendRedirect(request.getContextPath() +"/member/loginPre");
			return false;
		}else{
			//当cookies值失效时把session中的值传入cookies
			if(memberFromCookies==null){
				CookieUtils.setCookie(request, response, SessionContainer.MEMBER_INFO, CookieUtils.entityToString(memberFromSession),true);
			}
			if(memberFromSession==null){
				request.getSession().setAttribute(SessionContainer.sessionID + SID, memberFromCookies);
			}
		}
		return true;
	}
}
